<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息</p>
    </div>

    <div class="profile-content">
      <div class="profile-info">
        <div class="avatar-section">
          <div class="avatar-display">
            <img v-if="userInfo.userPicture && !userInfo.userPicture.startsWith('data:')" 
                 :src="userInfo.userPicture" 
                 alt="头像" />
            <div v-else-if="userInfo.userPicture && userInfo.userPicture.startsWith('data:')"
                 class="avatar-generated">
              <img :src="userInfo.userPicture" alt="头像" />
            </div>
            <div v-else class="avatar-initial">
              {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
            </div>
          </div>

        </div>

        <div class="info-display">
          <div class="info-item">
            <label>用户名</label>
            <span>{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <label>用户角色</label>
            <span>{{ userInfo.role === 1 ? '管理员' : '普通用户' }}</span>
          </div>
          <div class="info-item">
            <label>注册时间</label>
            <span>{{ formatDate(userInfo.createdAt) }}</span>
          </div>
          <div class="info-item">
            <label>最后更新</label>
            <span>{{ formatDate(userInfo.updatedAt) }}</span>
          </div>
        </div>
      </div>

      <div class="profile-edit">
        <el-form 
          :model="editForm" 
          :rules="rules" 
          ref="editFormRef" 
          label-width="100px"
          class="edit-form"
        >
          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="editForm.email" 
              placeholder="请输入邮箱"
              :disabled="!isEditing"
            />
          </el-form-item>

          <el-form-item label="个人简介" prop="bio">
            <el-input 
              v-model="editForm.bio" 
              type="textarea" 
              :rows="4"
              placeholder="请输入个人简介"
              :disabled="!isEditing"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <el-button v-if="!isEditing" type="primary" @click="startEdit">
              编辑信息
            </el-button>
            <template v-else>
              <el-button type="primary" @click="saveProfile" :loading="saving">
                保存
              </el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </template>
          </el-form-item>
        </el-form>

        <el-divider />

        <div class="password-section">
          <h3>修改密码</h3>
          <el-form 
            :model="passwordForm" 
            :rules="passwordRules" 
            ref="passwordFormRef" 
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password"
                placeholder="请确认新密码"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getProfile, updateProfile, changePassword as changePasswordApi } from '@/api/user'

const userStore = useUserStore()

const userInfo = ref({
  id: null,
  username: '',
  email: '',
  userPicture: '',
  bio: '',
  role: 0,
  createdAt: '',
  updatedAt: ''
})

const isEditing = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const editFormRef = ref()
const passwordFormRef = ref()

const editForm = reactive({
  email: '',
  bio: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  bio: [
    { max: 500, message: '个人简介不能超过500字符', trigger: 'blur' }
  ]
})

const passwordRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

onMounted(async () => {
  await loadUserProfile()
})

const loadUserProfile = async () => {
  try {
    const result = await getProfile({ userId: userStore.userInfo.id })
    if (result.success) {
      userInfo.value = result.data
      editForm.email = result.data.email
      editForm.bio = result.data.bio || ''
    } else {
      ElMessage.error(result.message || '获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const startEdit = () => {
  isEditing.value = true
}

const cancelEdit = () => {
  isEditing.value = false
  editForm.email = userInfo.value.email
  editForm.bio = userInfo.value.bio || ''
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
}

const saveProfile = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true

    const result = await updateProfile({
      userId: userInfo.value.id,
      email: editForm.email,
      bio: editForm.bio,
      userPicture: userInfo.value.userPicture
    })

    if (result.success) {
      ElMessage.success(result.message || '更新成功')
      userInfo.value = { ...userInfo.value, ...result.data }
      userStore.setUserInfo(result.data)
      isEditing.value = false
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true

    const result = await changePasswordApi({
      userId: userInfo.value.id,
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    if (result.success) {
      ElMessage.success(result.message || '密码修改成功')
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      if (passwordFormRef.value) {
        passwordFormRef.value.clearValidate()
      }
    } else {
      ElMessage.error(result.message || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error('密码修改失败')
  } finally {
    changingPassword.value = false
  }
}



const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
}

.profile-header h2 {
  color: var(--macaron-dark);
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.profile-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.profile-content {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 30px;
  align-items: start;
}

.profile-info {
  background: var(--macaron-white);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-display {
  margin-bottom: 15px;
}

.avatar-display img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid var(--macaron-mint);
}

.avatar-generated img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar-initial {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--macaron-purple), var(--macaron-blue));
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 36px;
  margin: 0 auto;
}

.info-display {
  space-y: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid var(--macaron-grey);
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 600;
  color: var(--macaron-dark);
  font-size: 14px;
}

.info-item span {
  color: #7f8c8d;
  font-size: 14px;
}

.profile-edit {
  background: var(--macaron-white);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.edit-form {
  margin-bottom: 20px;
}

.password-section h3 {
  color: var(--macaron-dark);
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
}

.password-form .el-form-item {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .profile-container {
    padding: 15px;
  }

  .profile-info,
  .profile-edit {
    padding: 20px;
  }
}
</style>
